package com.jdy.haoduoai.socket;

import android.content.Intent;
import android.util.Log;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.model.DownloadProgress;
import com.jdy.haoduoai.model.DownloadStateModel;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.SocketMachineInfo;
//import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class SocketThreadManager {

  private String TAG = SocketThreadManager.class.getSimpleName();
  private static SocketThreadManager s_SocketManager = null;

  private SocketInputThread mInputThread = null;
  // private SocketOutputThread mOutThread = null;
  private List<DeviceStateListener> mDeviceStateListeners;
  private List<DownloadStateListener> mDownloadStateListener;
  public boolean mDeviceHasUpgraded = false;
  private SocketHeartThread mHeartThread = null;

//  public static int PREFIX = 1;
//  public static int SUFFIX = 2;

  public List<DeviceStateListener> getDeviceStateListeners() {
    return mDeviceStateListeners;
  }

  public List<DownloadStateListener> getDownloadStateListener() {
    return mDownloadStateListener;
  }

  public List<OnDataReceivedListener> getOnDataReceivedListener() {
    return mOnDataReceivedListener;
  }

  private List<OnDataReceivedListener> mOnDataReceivedListener;

  public void removeDownloadStateListener(DownloadStateListener li) {
    this.mDownloadStateListener.remove(li);
  }

  public void setDownloadStateListener(DownloadStateListener li) {
    this.mDownloadStateListener.add(li);
  }

  public void setDeviceStateListener(DeviceStateListener deviceStateListener) {

    if (!mDeviceStateListeners.contains(deviceStateListener)) {
      this.mDeviceStateListeners.add(deviceStateListener);
    }

  }

  public void removeDeviceStateListener(DeviceStateListener deviceStateListener) {
    if (!mDeviceStateListeners.isEmpty() && mDeviceStateListeners.contains(deviceStateListener)) {
      this.mDeviceStateListeners.remove(deviceStateListener);
    }

  }

  public static SocketThreadManager getInstance() {
    if (s_SocketManager == null) {
      s_SocketManager = new SocketThreadManager();
      s_SocketManager.startThreads();
    }
    return s_SocketManager;
  }

  public void removeDataReceivedListener(OnDataReceivedListener li) {
    if (!mOnDataReceivedListener.isEmpty() && mOnDataReceivedListener.contains(li)) {
      this.mOnDataReceivedListener.remove(li);
    }
  }

  public void setDataReceivedListener(OnDataReceivedListener li) {
    if (!mOnDataReceivedListener.contains(li)) {
      this.mOnDataReceivedListener.add(li);
    }
  }

  private SocketThreadManager() {
    mDeviceStateListeners = new ArrayList<DeviceStateListener>();
    mDownloadStateListener = new ArrayList<DownloadStateListener>();
    mOnDataReceivedListener = new ArrayList<OnDataReceivedListener>();

    mHeartThread = new SocketHeartThread();
    mInputThread = new SocketInputThread();
    // mOutThread = new SocketOutputThread();
  }

  public void startThreads() {
    mHeartThread.start();
    mInputThread.start();
    mInputThread.setStart(true);
    // mOutThread.start();
    // mOutThread.setStart(true);
    // mDnsthread.start();
  }

  @SuppressWarnings("deprecation")
  public void stopThreads() {
    try {
      if (mHeartThread != null && mHeartThread.isAlive()) {
        mHeartThread.stopThread();
      }
    }catch (UnsupportedOperationException ee) {

    } catch (Exception e) {
      // TODO: handle exception
    }



    if (mInputThread != null) {
      mInputThread.setStart(false);
      try {
        mInputThread.stop();
      } catch (UnsupportedOperationException ee) {

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
    // mOutThread.setStart(false);
    // mOutThread.stop();
  }

  public void send(String msg) {
    try {
      TCPClient.instance().sendMsg(msg.replace("\\", "") + (char) 0);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void requestConnectDevice() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu == null) {
      lu = Tools.restoreLeUser();
    }
    if (lu != null) {
      try {
        JSONObject dataJson = new JSONObject();
        dataJson.put("code", 202);
        dataJson.put("act", "connect");
        dataJson.put("tel", lu.id);

        TCPClient.instance().sendMsg(dataJson.toString() + (char) 0);
      } catch (JSONException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public void requestDeviceDetails() {
    try {
//      JSONObject dataJson = new JSONObject();
//      dataJson.put("type", "machineinfo");
//      String getDetailsCmd = fabricateCommand(dataJson, 202);


      JSONObject dataJson = new JSONObject();
      dataJson.put("code", 202);
      dataJson.put("act", "machineinfo");

      TCPClient.instance().sendMsg(dataJson.toString() + (char) 0);
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void releaseInstance() {
    if (s_SocketManager != null) {
      s_SocketManager.stopThreads();
      s_SocketManager = null;
    }
  }

  /**
   * 
   * Update: 0 ---> not necessary 1 ---> necessary 2 ---> updating
   * 
   * @param jsonObject
   */
  private void parseMachineInfo(JSONObject jsonObject) {
    if (jsonObject.has("update")) {

//      final SocketMachineInfo sMInfo = JsonSerializer.getInstance()
//          .deserialize(jsonObject.toString(), SocketMachineInfo.class);

      final SocketMachineInfo sMInfo =GsonUtil.jsonToBean(jsonObject.toString(), SocketMachineInfo.class);

      if (sMInfo != null) {
        if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
          if (!SocketThreadManager.getInstance().mDeviceHasUpgraded) {
            for (DeviceStateListener dsl : SocketThreadManager.getInstance()
                .getDeviceStateListeners()) {
              dsl.onUpgrade(sMInfo.update);
            }
            SocketThreadManager.getInstance().mDeviceHasUpgraded = true;
          }

          if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
            for (DeviceStateListener dsl : SocketThreadManager.getInstance()
                .getDeviceStateListeners()) {
              dsl.onPowerChanged(sMInfo.power);
            }
          }
        }

        Intent macInfoChangedIntent = new Intent("device.details.update.event");
        macInfoChangedIntent.putExtra("socketmachineinfo", sMInfo);
        LeXiaoXiaoBanApp.getAppContext().sendBroadcast(macInfoChangedIntent);
      }
    }
  }

  /**
   * Ensure the integer is valid.
   * 
   * @param version
   */
  @SuppressWarnings("unused")
  private void checkIfDeviceMatch(String version) {
    try {
      int currentDeviceVersion = Integer
          .valueOf(version.replaceAll("\\D+", ""));
      if (currentDeviceVersion < 201) {
        LeConfig.isDeviceVersionMatch = false;
      } else {
        LeConfig.isDeviceVersionMatch = true;
        // LePreferences le = StoreBox.create(this, LePreferences.class);
        // le.setDeviceVersion(version);
      }
    } catch (NumberFormatException nfe) {
      return;
    }
  }

//  private String fabricateCommand(JSONObject content, int codeValue) {
//    JSONObject rawCommand = new JSONObject();
//    try {
//      rawCommand.put("data", content);
//      rawCommand.put("code", codeValue);
//    } catch (JSONException e) {
//
//      e.printStackTrace();
//    }
//    String commandString = (char) PREFIX + rawCommand.toString()
//        + (char) SUFFIX;
//    return commandString;
//  }

//  public void requestUpgrade() {
//
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "update");
//      String updateCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", updateCmd);
//
//      TCPClient.instance().sendMsg(updateCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }
//
//  public void playNext() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "next");
//      String nextCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", nextCmd);
//      TCPClient.instance().sendMsg(nextCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

//  public void playForward() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "speed");
//      String nextCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", nextCmd);
//
//      TCPClient.instance().sendMsg(nextCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

//  public void playRewind() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "rewind");
//      String nextCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", nextCmd);
//      TCPClient.instance().sendMsg(nextCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

//  public void playPrev() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "prev");
//      String prevCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", prevCmd);
//      TCPClient.instance().sendMsg(prevCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

  public void disconnectOldConnectNew() {
    TCPClient.instance().disconnectOldConnectNew();
  }

//  public void sendDeleteCmd(String usrid, String machineId, String ids) {
//    // if (null == mSocket) {
//    // initSocket();
//    // return;
//    // }
//
//    try {
//      JSONObject dataJson = new JSONObject();
//      dataJson.put("macid", usrid);
//      dataJson.put("op", "delete");
//      dataJson.put("to", machineId);
//      dataJson.put("id", ids);
//
//      String getDetailsCmd = fabricateCommand(dataJson, 130);
//      Log.e("socket", getDetailsCmd);
//      TCPClient.instance().sendMsg(getDetailsCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

//  public void startLiveShow() {
//    JSONObject jsonObject = new JSONObject();
//    try {
//      jsonObject.put("macid", LeConfig.PHONE_NUM);
//      jsonObject.put("to", LeConfig.MAC_ID);
//      jsonObject.put("op", "watchbaby");
//      jsonObject.put("content", "start");
//      String connCmd = fabricateCommand(jsonObject, 130);
//
//      TCPClient.instance().sendMsg(connCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

  /**
   * 获取下载列表
   * 
   * @param macid
   * @param machineId
   * @param attr
   * @param downloadState
   * @param page
   */
//  public void requestDownloadList(String macid, String machineId, String attr,
//      String downloadState, int page) {
//    // if (null == mSocket) {
//    // initSocket();
//    // return;
//    // }
//
//    try {
//      JSONObject dataJson = new JSONObject();
//      dataJson.put("macid", macid);
//      dataJson.put("op", "getdownloadlist");
//      dataJson.put("to", machineId);
//      dataJson.put("attribute", attr);
//      dataJson.put("downloadstate", downloadState);
//      dataJson.put("page", page);
//
//      String getDetailsCmd = fabricateCommand(dataJson, 130);
//      Log.e("socket", getDetailsCmd);
//      TCPClient.instance().sendMsg(getDetailsCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

  /**
   * 设备下载
   *          下载故事id
   *          封面
   */
//  public void sendDownloadCmd(String usrid, String machineId, AlbumItem ai,
//      String attr, String downloadact) {
//    // if (null == mSocket) {
//    // initSocket();
//    // return;
//    // }
//
//    try {
//      JSONObject dataJson = new JSONObject();
//      dataJson.put("macid", usrid);
//      dataJson.put("op", "download");
//      dataJson.put("to", machineId);
//      dataJson.put("id", ai.id);
//      dataJson.put("url", ai.url);
//      dataJson.put("name", ai.album_name);
//      dataJson.put("title", ai.title);
//      dataJson.put("attribute", attr);
//      dataJson.put("downloadact", downloadact);
//      dataJson.put("pic", ai.album_cover);
//
//      String getDetailsCmd = fabricateCommand(dataJson, 130);
//      Log.e("socket", getDetailsCmd);
//      TCPClient.instance().sendMsg(getDetailsCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }
//
//  public void stopLiveShow() {
//    JSONObject jsonObject = new JSONObject();
//    try {
//      jsonObject.put("macid", LeConfig.PHONE_NUM);
//      jsonObject.put("to", LeConfig.MAC_ID);
//      jsonObject.put("op", "watchbaby");
//      jsonObject.put("content", "stop");
//      String connCmd = fabricateCommand(jsonObject, 130);
//  //    Log.e("TAG send 130=================>", connCmd);
//      TCPClient.instance().sendMsg(connCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

//  public void playPause() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "pause");
//      String pauseCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", pauseCmd);
//
//      TCPClient.instance().sendMsg(pauseCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }
//
//  public void playResume() {
//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("type", "cartoon");
//      jsonObject.put("op", "resume");
//      String resumeCmd = fabricateCommand(jsonObject, 202);
//      Log.e("socket", resumeCmd);
//      TCPClient.instance().sendMsg(resumeCmd.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//  }

  private void parseVoiceMessageResponse(JSONObject jsonObject) {
    if (jsonObject.has("stream")) {
      try {
        String voiceUrl = jsonObject.getString("stream");
        if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
          for (DeviceStateListener dsl : SocketThreadManager.getInstance()
              .getDeviceStateListeners()) {
            dsl.onReceivedVoiceMessage(voiceUrl);
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  private void parseDeviceActionResponse(JSONObject jsonObject) {
    if (jsonObject.has("type")) {
      try {
        String actionType = jsonObject.getString("type");
        if ("cartoon".equals(actionType) || "story".equals(actionType)
            || "radio".equals(actionType) || "dub".equals(actionType)
            || "mine_story".equals(actionType) || "book".equals(actionType)
            || "education".equals(actionType)) {
          Log.e(TAG, "video data info from device===>" + jsonObject.toString());
          parseCartoonInfo(jsonObject);
        } else if ("machineinfo".equals(actionType)) {
          Log.e(TAG,
              "machineinfo data info from device===>" + jsonObject.toString());
          parseMachineInfo(jsonObject);
        } else if ("radio".equals(actionType)) {
          Log.e(TAG, "radio data info from device===>" + jsonObject.toString());
          parseRadioInfo(jsonObject);
        } else if ("pre".equals(actionType)) {
          if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
            for (DeviceStateListener dsl : SocketThreadManager.getInstance()
                .getDeviceStateListeners()) {
              dsl.onPlayPrevFailed();
            }
          }
        } else if ("next".equals(actionType)) {
          if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
            for (DeviceStateListener dsl : SocketThreadManager.getInstance()
                .getDeviceStateListeners()) {
              dsl.onPlayNextFailed();
            }
          }
        } else if ("downloadstate".equals(actionType)) { // 下载进度
          parseDownloadStateInfo(jsonObject);
        } else if ("getdownloadlist".equals(actionType)) {
          parseDownloadListInfo(jsonObject);
        } else if ("downloadsize".equals(actionType)) {
          if (jsonObject.has("size")) {
            if (SocketThreadManager.getInstance().getDownloadStateListener() != null) {
              for (DownloadStateListener dsl : SocketThreadManager
                  .getInstance().getDownloadStateListener()) {
                dsl.downLoadSize(jsonObject.getInt("size"));
              }
            }
          }
        } else {
          Log.e(TAG, "other data info from device===>" + jsonObject.toString());
          parseOtherInfo(jsonObject);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    } else {// when there is no type in the content!
      parseNoTypeInfo(jsonObject);
    }
  }

  private void parseDownloadListInfo(JSONObject jsonObject) {
//    JsonSerializer.getInstance().deserialize(
//        jsonObject.toString(), DownloadStateModel.class);

    final DownloadStateModel data = GsonUtil.jsonToBean(jsonObject.toString(), DownloadStateModel.class);

    if (SocketThreadManager.getInstance().getDownloadStateListener() != null) {
      for (DownloadStateListener dsl : SocketThreadManager.getInstance()
          .getDownloadStateListener()) {
        dsl.onDownloadList(data);
      }
    }
  }

  private void parseRadioInfo(JSONObject jsonObject) {
    String playState;
    try {
      playState = jsonObject.getString("PlayState");
      PlayState state = getPlayStateByString(playState);
      if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
        for (DeviceStateListener dsl : SocketThreadManager.getInstance()
            .getDeviceStateListeners()) {
          dsl.onPlayMedia(state, MediaType.Radio, jsonObject);
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  private void parseCartoonInfo(JSONObject jsonObject) {
    try {
      if (jsonObject.has("VideoId")) {
        int id = jsonObject.getInt("VideoId");
        if (id == -1)
          return;
      }
      String playState = jsonObject.getString("PlayState");
      PlayState state = getPlayStateByString(playState);
      if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
        for (DeviceStateListener dsl : SocketThreadManager.getInstance()
            .getDeviceStateListeners()) {
          dsl.onPlayMedia(state, MediaType.Collection, jsonObject);
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  private void parseNoTypeInfo(JSONObject jsonObject) {
    try {
      String playState;
      playState = jsonObject.getString("PlayState");
      PlayState state = getPlayStateByString(playState);
      if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
        for (DeviceStateListener dsl : SocketThreadManager.getInstance()
            .getDeviceStateListeners()) {
          dsl.onPlayMedia(state, MediaType.NoType, jsonObject);
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  private void parseHeartbeat(JSONObject jsonObject) {
    if (jsonObject.has("type")) {
      try {
        String connectResult = jsonObject.getString("type");
        Log.e(TAG, "Heartbeat ====>" + connectResult);
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  @SuppressWarnings("unused")
  private void parseConnection(JSONObject jsonObject) {
    if (jsonObject.has("type")) {
      try {
        String connectResult = jsonObject.getString("type");
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  private PlayState getPlayStateByString(String state) {
    if ("playing".equals(state)) {
      return PlayState.Playing;
    } else if ("pause".equals(state)) {
      return PlayState.Pause;
    } else if ("stop".equals(state)) {
      return PlayState.Stop;
    }
    return PlayState.None;
  }

  private void parseOtherInfo(JSONObject jsonObject) {
    String playState;
    try {
      playState = jsonObject.getString("PlayState");
      PlayState state = getPlayStateByString(playState);
      if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
        for (DeviceStateListener dsl : SocketThreadManager.getInstance()
            .getDeviceStateListeners()) {
          dsl.onPlayMedia(state, MediaType.OtherType, jsonObject);
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  /**
   * 解析下载进度
   * 
   * @param jsonObject
   */
  private void parseDownloadStateInfo(JSONObject jsonObject) {
//    final DownloadProgress data = JsonSerializer.getInstance().deserialize(
//        jsonObject.toString(), DownloadProgress.class);

    final DownloadProgress data =GsonUtil.jsonToBean(jsonObject.toString(), DownloadProgress.class);

    if (SocketThreadManager.getInstance().getDownloadStateListener() != null) {
      for (DownloadStateListener dsl : SocketThreadManager.getInstance()
          .getDownloadStateListener()) {
        dsl.onDownloadState(data);
      }
    }
  }

  @SuppressWarnings("unused")
  private void handleAct(String data) {
    try {
      JSONObject jsonData = new JSONObject(data.toString());
      int retCode = -1;
      if (!jsonData.isNull("code")) {
        retCode = jsonData.getInt("code");
        switch (retCode) {
        case -3:
          SocketThreadManager.getInstance().stopThreads();
          // exitSocketConn();
          if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
            for (DeviceStateListener dsl : SocketThreadManager.getInstance()
                .getDeviceStateListeners()) {
              dsl.onRemoteLogin();
            }
          }
          break;
        case 140:
          if (!jsonData.isNull("data") && data.toString().length() < 25) {
            // 0在线 1离线
            LeConfig.isDeviceOnline = jsonData.getInt("data");

            if (LeConfig.isDeviceOnline == 0) {
              LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
              LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
              if (lu != null && lb != null) {

             //   if (mImHelper.isLogin()) {
                //  mImHelper.connect(lb.id);

//                  JSONObject jsonObject = new JSONObject();
//                  try {
//                    jsonObject.put("code", 202);
//                    jsonObject.put("act", "connect");
//                    jsonObject.put("data", lu.id);
//
//                    SocketThreadManager.getInstance().send(jsonObject.toString());
//                  } catch (JSONException e) {
//                    e.printStackTrace();
//                  }
            //    }
              }
            }
          }
          break;
        case 100:
          if (jsonData.has("type")) {
            if ("connect".equals(jsonData.getString("type"))) {
              LeConfig.isDeviceConnect = true;
              if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
                for (DeviceStateListener dsl : SocketThreadManager
                    .getInstance().getDeviceStateListeners()) {
                  dsl.onConnectionChanged(true);
                }
              }
              requestDeviceDetails();
            } else {
              LeConfig.isDeviceConnect = false;
              if (SocketThreadManager.getInstance().getDeviceStateListeners() != null) {
                for (DeviceStateListener dsl : SocketThreadManager
                    .getInstance().getDeviceStateListeners()) {
                  dsl.onConnectionChanged(false);
                }
              }
            }
          }
          break;
        case 102:
          if (jsonData.has("data")) {
            parseDeviceActionResponse(jsonData.getJSONObject("data"));
          }
          break;
        case 110:
          break;
        case 120: // SOCKET语音包
          if (jsonData.has("data")) {
            parseVoiceMessageResponse(jsonData.getJSONObject("data"));
          }
          break;
        case 130:
          break;
        case 150: // rtmp连接状态
          // parseRtmpConnection(jsonData.getJSONObject("data"));
          // TODO
          break;
        case 200:// SOCKET连接包
          if (jsonData.has("data"))
            parseConnection(jsonData.getJSONObject("data"));
          break;
        case 202:// SOCKET操作包
          // if (jsonData.has("data"))
          // parserActionResponse(jsonData.getJSONObject("data"));
          break;
        case 210:// SOCKET心跳包
          if (jsonData.has("data"))
            parseHeartbeat(jsonData);
          break;
        default:
          break;
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

  }
}
